package com.xiongjie.SingleLimit.algorithm;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * 固定窗口+多线程限流算法
 */
public class FWLimiter implements Limiter, Runnable {

    //这是全局变量，原子性
    private AtomicInteger count=new AtomicInteger(0) ;

    @Override
    public int currentQPS() {
        return count.get();
    }

    @Override
    public boolean isOverLimit() {
        return currentQPS() > 5;
    }

    @Override
    public boolean visit() {
        count.incrementAndGet();
        return isOverLimit();
    }

    @Override
    public void run() {
        System.out.println(this.currentQPS());
        count.set(0);
    }

    /**
     * 一个4个线程，main线程，负责启动另外3个线程
     * 2个匿名线程，负责模拟0.1秒1次的发送访问请求
     * 1个执行器线程，负责定时1秒1次的清空全局原子变量
     *
     * @param args 主函数参数
     */
    public static void main(String[] args) {

        //线程执行器，设定定时时间，1秒钟执行一次.🌿🌿🌿
        FWLimiter rateLimiter = new FWLimiter();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(rateLimiter, 0, 1, TimeUnit.SECONDS);

        //模拟0.1秒中发送一次请求
        IntStream.range(0, 2).forEach(i -> {
            new Thread(() -> {
                while (true) {
                    boolean res = rateLimiter.visit();
                    System.out.print(res + "\t");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        });
    }
}
